#include <cstdio>
#include <cstring>
#include <vector>
#include <sstream>
#include "cStream.h"




void cStream::writeByte( unsigned char v ) {
	data.push_back(v);
}
	
void cStream::writeShort( unsigned short v ) {
	data.push_back( (unsigned char)(v & 0xff) );
	data.push_back( (unsigned char)((v & 0xff00) >> 8) );
}
	
void cStream::writeInt( unsigned int v ) {
	data.push_back( (unsigned char)(v & 0x000000ff) );
	data.push_back( (unsigned char)((v & 0x0000ff00) >> 8) );
	data.push_back( (unsigned char)((v & 0x00ff0000) >> 16) );
	data.push_back( (unsigned char)((v & 0xff000000) >> 24) );
}
	
void cStream::writeString( std::string v ) {
	if(v.length() < 32768) {
		writeShort( (ushort)v.length() ); // first byte never has 1xxx xxxx pattern -> short
	}else{
		writeInt( 0x80000000 | v.length() ); // first byte always has 1xxx xxxx pattern -> int
	}
	data.reserve(data.size() + v.length());
	for( unsigned int i = 0; i < v.length(); i ++ ) {
		data.push_back(v[i]);
	}
}

const packet_data cStream::getBuffer() {
	packet_data data;

#if DEBUG
	if(this->data.size() < 1)
		log_net_debug("packet data size < 1!");
#endif

	unsigned char* p = (unsigned char*) malloc( this->data.size() );
	memcpy( p, &(this->data[0]), this->data.size() );
	data.data = p;
	data.length = this->data.size();
	return data;
}

int cStream::getStringLength( std::string s ) {
	return s.length() < 32768 ? s.length() + 2 : s.length() + 4;
}

unsigned char cStream::getFirstByte() {
	if(data.size() < 1) return 250;
	return data[0];
}
